package com.moonlight.mina;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
//@Component
public class MinaRunning implements CommandLineRunner{
	private final static Logger logger = LoggerFactory.getLogger(MinaRunning.class);
	
	private final static String ADDRESS = "localhost";
	
	private final static int PORT = 3000;

	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		NioSocketConnector connector = new NioSocketConnector();
		connector.getSessionConfig().setBothIdleTime(10);
		connector.getSessionConfig().setSendBufferSize(1024);
		connector.getSessionConfig().setReceiveBufferSize(1024);
		connector.getFilterChain().addLast("codec" , new ProtocolCodecFilter(new MinaEncodingFactory(Charset.forName("utf-8"))));
		connector.setHandler(new MinaHandler());
		ConnectFuture connectFuture = connector.connect(new InetSocketAddress(ADDRESS , PORT));
		connectFuture.addListener(new IoFutureListener<IoFuture>() {

			@Override
			public void operationComplete(IoFuture future) {
				// TODO Auto-generated method stub
				IoSession session = future.getSession();
				for(int i = 0 ; i < 10 ; i ++) {
					session.write(new MinaPackage((byte)i , "你好服务端"));
				}
			}
			
		});
	}
	
}
